package cn.xshi.route.publisher;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import org.springframework.stereotype.Component;

/**
 * @Desc I/O事件处理类
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Component
public class GatewayServerChannelInitializer extends ChannelInitializer<SocketChannel> {

    /**
     *
     */
    GatewayChannelUtil gatewayChannelUtil;

    /**
     *
     */
    public GatewayServerChannelInitializer(){

    }

    /**
     *
     * @param gatewayChannelUtil
     */
    public GatewayServerChannelInitializer(GatewayChannelUtil gatewayChannelUtil){
        this.gatewayChannelUtil = gatewayChannelUtil;
    }

    /**
     *
     * @param socketChannel
     * @throws Exception
     */
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        //添加编解码
        //ProtobufVarint32LengthFieldPrepender，ProtobufVarint32FrameDecoder解决大字符串粘包、拆包问题
        socketChannel.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender());
        socketChannel.pipeline().addLast(new ProtobufVarint32FrameDecoder());
        socketChannel.pipeline().addLast(new ProtobufEncoder());
        socketChannel.pipeline().addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
        socketChannel.pipeline().addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
        socketChannel.pipeline().addLast(new GatewayNettyServerHandler(gatewayChannelUtil));
        /**
         * maxFrameLength: 解码的帧的最大长度，超过此长度的帧将被丢弃。
         * lengthFieldOffset: 长度字段在帧中的偏移量，表示长度字段的起始位置。
         * lengthFieldLength: 长度字段的长度，通常为 2、4、8 等字节。
         * lengthAdjustment: 长度字段的值与帧的实际长度之间的偏差值。
         * initialBytesToStrip: 解码后，从帧中跳过的字节数。
         */
        /*socketChannel.pipeline().addLast(new LengthFieldPrepender(4));
        socketChannel.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024, 0, 4, 0, 4));
        socketChannel.pipeline().addLast(new JsonMessageDecoder());
        socketChannel.pipeline().addLast(new JsonMessageEncoder());*/
    }
}
